import API from '../../api/api.js'
const FORMAT = require('../../api/util.js')
import Dialog from '../../lib/vant-weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    picker: ['请选择心情分类', '期待鼓励', '期待支持', '迷茫抉择', '两性感情', '真实故事', '办公秩事', '限时心情'],
    formats: {},
    readOnly: false,
    placeholder: '此为富文本编辑器，段落【首行缩进】系统会自动添加，可编辑标题、加粗、换行、插入图片等，开始输入文章内容...发布【限时心情】的时候，时效为3天。系统自动处理。',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    wenZhangShuJu: {
      tiMu: "",
      leiXing: "",
      biMing: "",
      leiXingIndex: 0,
      neiRong: "",
      jianJie: "",
      chuangJianShiJian: "",
      jieShuShiJian: "",
      pinLun: [],
      wenZhangImagesList: []
    }
  },

  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '发布文章'
    })

    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS
    })
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },

  onShow: function () {
    let tempdata = wx.getStorageSync('curWenZhang')
    if (tempdata != "") {
      this.data.wenZhangShuJu = tempdata
      this.setData({
        tiMu: tempdata.tiMu,
        index: tempdata.leiXingIndex
      })
    }
  },

  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const {
      windowHeight,
      platform
    } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({
      editorHeight,
      keyboardHeight
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    let tempdata = wx.getStorageSync('curWenZhang')
    that.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
      if (tempdata != "") {
        that.editorCtx.setContents({
          html: tempdata.neiRong
        })
      }
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format: function (e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {}
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {}
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },

  getImageInfo: function (path) {
    return new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: path,
        success(res) {
          resolve(res.type)
        },
        fail: err => {
          reject("获取数据出错了，请重试！")
          console.error(err)
        }
      })
    })
  },

  async insertImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      success: async function (res) {
        let tempfile = res.tempFilePaths[0]
        wx.showLoading({
          title: '正在检测图片内容...',
          mask: true
        })
        await API.checkImageContent(res.tempFilePaths[0]).then(res => {
          if (res.result.errCode == 87014) {
            wx.showToast({
              title: '您的图片内有违规内容，请更换图片，请谅解。',
              icon: "none"
            })
            wx.hideLoading()
            return
          }
          wx.hideLoading()
          wx.showLoading({
            title: '正在加载...',
            mask: true
          })
          that.getImageInfo(tempfile).then(res => {
            let fileName = "wenzhangimages/" + new Date().getTime() + "." + res
            wx.cloud.uploadFile({
              cloudPath: fileName,
              filePath: tempfile,
            }).then(res => {
              that.data.wenZhangShuJu.wenZhangImagesList.push(res.fileID)
              that.editorCtx.insertImage({
                src: res.fileID,
                width: '100%',
                success: function () {
                  wx.hideLoading()
                  wx.showToast({
                    title: '图片插入成功！',
                    icon: "success",
                    duration: 2000
                  })
                }
              })
            })
          }).catch(error => {
            // handle error
          })
        })
      }
    })
  },
  onFocus: function (e) {},
  onInput: async function (e) {
    this.data.wenZhangShuJu.neiRong = e.detail.html
    this.data.wenZhangShuJu.jianJie = e.detail.text.substring(0, 50)
    this.setData({
      neiRong: e.detail.html
    })
  },
  onBlur: function (e) {},


  onTiMuInput: function (e) {
    this.data.wenZhangShuJu.tiMu = e.detail.value
  },
  onTiMuBlur: function (e) {},
  leiXingChange(e) {
    let index = Number(e.detail.value)
    this.setData({
      index: index
    })
    this.data.wenZhangShuJu.leiXing = this.data.picker[index]
    this.data.wenZhangShuJu.leiXingIndex = index
  },

  onFaBu: async function (e) {
    wx.showLoading({
      title: '正在检测内容。',
      icon: "none",
      mask: true
    })
    await API.checkWenZhiNeiRong(this.data.neiRong).then(res => {
      if (res.result.errCode === 87014) {
        wx.showToast({
          title: '您的文章内有违规内容，请更换图片，请谅解。',
          icon: "none"
        })
        wx.hideLoading()
        return
      }
      wx.hideLoading()
      Dialog.confirm({
          title: '发表心情',
          message: '请确定是否发表此心情文章。'
        })
        .then(() => {
          const that = this
          let data = this.data.wenZhangShuJu
          let userInfo = wx.getStorageSync('userInfo')
          let wenzhangstorage = wx.getStorageSync('currWenZhang')
          data.biMing = userInfo.biMing
          if (data.leiXing == "限时心情") {
            data.jieShuShiJian = FORMAT.formatDay((new Date().getTime() + 3 * 86400000) / 1000)
          }
          data.chuangJianShiJian = FORMAT.formatDay(Math.floor(new Date().getTime() / 1000))
          if (wenzhangstorage == "") {
            let content = data.neiRong.replace(/<p/g, '<p style="text-indent: 1em;" ').replace(/<img/g, '<img style="text-indent: none !important;" ')
            data.neiRong = content
          }
          if (data.leiXing != "" && data.biMing != "" && data.tiMu != "" && data.jianJie.length > 20) {
            API.tianJiaShuJu('wenzhangbiao', data).then(res => {
              wx.removeStorageSync('curWenZhang')
              that.clear()
              wx.redirectTo({
                url: "/pages/wenzhangdetail/wenzhangdetail?id=" + res + "&mode=fabiao"
              })
            })
          } else {
            wx.showToast({
              title: '心情文章数据不完整,或者文章字数不满20字，请添加完整再发布。',
              icon: "none"
            })
          }
        })
        .catch(err => {
          console.error(err)
          wx.showToast({
            title: '已经取消发表心情文章。',
            icon: "none"
          })
        })
    })
  },

  onSave: function (e) {
    wx.showToast({
      title: '临时数据已保存草稿,点击发布后清理草稿。',
      icon: "none",
      duration: 2000
    })
    wx.setStorageSync('curWenZhang', this.data.wenZhangShuJu)
  }

})